package com.sj.parksdk.fragment.carmanage;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.view.View;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.android.vlayout.layout.LinearLayoutHelper;
import com.ruffian.library.widget.RLinearLayout;
import com.ruffian.library.widget.RTextView;
import com.ruffian.library.widget.helper.RBaseHelper;
import com.ruffian.library.widget.helper.RTextViewHelper;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;
import com.sj.parksdk.R;
import com.sj.parksdk.R2;
import com.sj.parksdk.adapter.base.delegate.SimpleDelegateAdapter;
import com.sj.parksdk.core.BaseFragment;
import com.sj.parksdk.core.http.subscriber.TipRequestSubscriber;
import com.sj.parksdk.fragment.pay.FragmentPayResult;
import com.sj.parksdk.fragment.profile.FragmentAvailableCoupons;
import com.sj.parksdk.model.bean.PicPreInfo;
import com.sj.parksdk.net.base.CommonResult;
import com.sj.parksdk.net.http.ApiHelper;
import com.sj.parksdk.net.http.MyNetApi;
import com.sj.parksdk.net.http.callback.TipRequestCallBack;
import com.sj.parksdk.net.manager.TokenManager;
import com.sj.parksdk.net.request.MGetRequest;
import com.sj.parksdk.net.result.databean.Data_Car;
import com.sj.parksdk.net.result.databean.Data_Order_Pics;
import com.sj.parksdk.net.result.databean.Data_ParkRecord;
import com.sj.parksdk.net.result.databean.Data_Weipay_Native;
import com.sj.parksdk.setting.Dictionary;
import com.sj.parksdk.setting.Extras;
import com.sj.parksdk.utils.RefreshState;
import com.sj.parksdk.utils.XToastUtils;
import com.sj.parksdk.widget.sweetalert.SweetAlertDialog;
import com.xuexiang.xaop.annotation.SingleClick;
import com.xuexiang.xhttp2.XHttp;
import com.xuexiang.xhttp2.exception.ApiException;
import com.xuexiang.xhttp2.request.CustomRequest;
import com.xuexiang.xpage.annotation.Page;
import com.xuexiang.xpage.core.PageOption;
import com.xuexiang.xqrcode.XQRCode;
import com.xuexiang.xrouter.annotation.AutoWired;
import com.xuexiang.xrouter.launcher.XRouter;
import com.xuexiang.xui.adapter.recyclerview.RecyclerViewHolder;
import com.xuexiang.xui.utils.DensityUtils;
import com.xuexiang.xui.utils.ResUtils;
import com.xuexiang.xui.utils.WidgetUtils;
import com.xuexiang.xui.widget.imageview.preview.PreviewBuilder;
import com.xuexiang.xui.widget.statelayout.StatefulLayout;
import com.xuexiang.xutil.common.StringUtils;
import com.xuexiang.xutil.data.DateUtils;
import com.xuexiang.xutil.net.JsonUtil;

import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

import static android.app.Activity.RESULT_OK;

@Page(name = "停车记录", params = {Extras.CAR_ID, Extras.CAR_COLOR, Extras.CAR_IS_CETIFICAT, Extras.CAR_NUMBER, Extras.PARK_ORDER_UNFINISH})
public class FragmentParkRecord extends BaseFragment {
    @BindView(R2.id.tv_name)
    TextView tvName;
    @BindView(R2.id.rtv_car_color)
    RTextView rtvCarColor;
    RTextViewHelper rtvCarColorHelper;
    @BindView(R2.id.rll_car_color)
    RLinearLayout rllCarColor;
    RBaseHelper rllCarColorHelper;
    @BindView(R2.id.tv_cetificat)
    RTextView tvCetificat;
    @BindView(R2.id.recycler_record)
    RecyclerView recyclerRecord;
    @BindView(R2.id.refresh)
    SmartRefreshLayout refresh;
    @BindView(R2.id.ll_state)
    StatefulLayout llState;

    @AutoWired(name = Extras.CAR_ID)
    long carId;
    @AutoWired(name = Extras.CAR_NUMBER)
    String number;
    @AutoWired(name = Extras.CAR_IS_CETIFICAT)
    boolean carIsCetificat;
    @AutoWired(name = Extras.CAR_COLOR)
    String color;
    @AutoWired(name = Extras.PARK_ORDER_UNFINISH)
    boolean orderUnfinish;


    private SimpleDelegateAdapter<Data_ParkRecord> adapterRecords;
    private DateFormat mDateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");

    @Override
    protected int getLayoutId() {
        return R.layout.parksdk_fragment_park_record;
    }

    @Override
    protected void initArgs() {
        XRouter.getInstance().inject(this);
    }

    @Override
    protected void initViews() {
        initCarInfo();
        initRecordAdapter();
    }

    private void initCarInfo() {
        tvName.setText(number);
        rtvCarColorHelper = rtvCarColor.getHelper();
        rtvCarColorHelper.setBackgroundColorNormal(ResUtils.getColor(Dictionary.Car.PlateColor.PalteColorMap.get(color)));
        rtvCarColorHelper.setTextColorNormal(ResUtils.getColor(Dictionary.Car.PlateColor.White.equals(color) ? R.color.color_3 : R.color.color_white));
        rtvCarColorHelper.setBorderWidthNormal(DensityUtils.dp2px(Dictionary.Car.PlateColor.White.equals(color) ? 1 : 0));
        rtvCarColor.setText(Dictionary.Car.PlateColor.PlateColorNameMap.get(color));
        rllCarColorHelper = rllCarColor.getHelper();
        rllCarColorHelper.setBorderColorNormal(ResUtils.getColor(Dictionary.Car.PlateColor.White.equals(color) ? R.color.color_3 : Dictionary.Car.PlateColor.PalteColorMap.get(color)));
        tvCetificat.setVisibility(carIsCetificat ? View.VISIBLE : View.GONE);
    }

    private void initRecordAdapter() {
        adapterRecords = new SimpleDelegateAdapter<Data_ParkRecord>(R.layout.parksdk_adapter_park_record, new LinearLayoutHelper()) {
            @Override
            protected void bindData(@NonNull RecyclerViewHolder holder, int position, Data_ParkRecord item) {
                holder.text(R.id.tv_address, item.getParkingLotName());
                holder.text(R.id.tv_start_time, DateUtils.millis2String(item.getChargeBeginTime(), mDateFormat));
                holder.text(R.id.tv_end_time, item.getChargeEndTime() == 0 ? "尚未结束" : DateUtils.millis2String(item.getChargeEndTime(), mDateFormat));
                holder.text(R.id.tv_length, item.getChargeTime());

                if (item.getState() == Dictionary.Park.State.finish || item.getState() == Dictionary.Park.State.agency) {
                    holder.visible(R.id.bt_pay, View.GONE);
                    holder.visible(R.id.tv_alredy_pay, View.VISIBLE);
                    holder.text(R.id.tv_total, "¥ " + item.getTotalFee().toString());
                    holder.text(R.id.tv_coupons, "－ ¥" + item.getTotalDiscountFee().toString());
                    holder.visible(R.id.iv_coupons_next, View.GONE);
                    holder.text(R.id.tv_price, item.getTotalFee().toString());
                } else {
                    holder.visible(R.id.bt_pay, item.getServiceFee().compareTo(new BigDecimal("0.00")) == 1 ? View.VISIBLE : View.GONE);
                    holder.visible(R.id.tv_alredy_pay, View.GONE);
                    holder.text(R.id.tv_total, "¥ " + item.getPayFee().toString());
                    holder.visible(R.id.iv_coupons_next, View.VISIBLE);
                    holder.text(R.id.tv_price, item.getServiceFee().toString());
                    if (item.getDiscountFee() == null || item.getDiscountFee().compareTo(new BigDecimal("0")) == 0) {
                        if (item.getCoupons() == null || item.getCoupons().size() == 0)
                            holder.text(R.id.tv_coupons, "无可用");
                        else holder.text(R.id.tv_coupons, item.getCoupons().size() + "张可用");
                    } else {
                        holder.text(R.id.tv_coupons, "－ ¥" + item.getDiscountFee().toString());
                    }
                }
                //click
                holder.click(R.id.tv_coupons, v -> gotoCoupons(position));
                holder.click(R.id.bt_pay, v -> gotoPay(item));
                holder.click(R.id.iv_pic, v -> queryOrderPic(item.getOrderNo()));
            }
        };
        WidgetUtils.initRecyclerView(recyclerRecord, DensityUtils.dp2px(10), ResUtils.getColor(R.color.color_cut_line));
        recyclerRecord.setAdapter(adapterRecords);
    }

    private void queryOrderPic(String orderNo) {
        new MGetRequest(MyNetApi.PARK_ORDER_PICS + orderNo + "/pirtures")
                .user()
                .execute(new TipRequestCallBack<Data_Order_Pics>() {
                    @Override
                    public void onSuccess(Data_Order_Pics response) throws Throwable {
                        showPics(response);
                    }
                });
    }

    private void showPics(Data_Order_Pics response) {
        List<String> pic = new ArrayList<>();
        if(response.getInPirtures()!=null )pic.addAll(response.getInPirtures());
        if(response.getOutPirtures()!=null)pic.addAll(response.getOutPirtures());
        if(pic.size() == 0){
            XToastUtils.warning("暂无图片");
            return;
        }
        List<PicPreInfo> pics = new ArrayList<>();
        for (String url:pic
             ) {
            pics.add(new PicPreInfo(url));
        }
        PreviewBuilder.from(getActivity())
                .setImgs(pics)
                .setCurrentIndex(0)
                .setSingleFling(true)
                .setProgressColor(R.color.app_color_theme_main)
                .setType(PreviewBuilder.IndicatorType.Number)
                .start();

    }

    private void gotoPay(Data_ParkRecord item) {
        if (item.getPayFee().compareTo(new BigDecimal("0.00")) == 1) weiPay(item);
        else noneedPay(item);
    }

    /**
     * 调用小计金额为0时的接口
     *
     * @param item
     */
    @SuppressLint("CheckResult")
    private void noneedPay(Data_ParkRecord item) {
        CustomRequest request = XHttp.custom();
        request.call(ApiHelper.getInstance(request)
                .payFreeTrade(item.getTradeNo(), item.getTimestamp(), item.getSign()))
                .subscribeWith(new TipRequestSubscriber<CommonResult>() {
                    @Override
                    protected void onSuccess(CommonResult result) {
                        if (result.getCode() == 200) {
                            refresh.autoRefresh();
                            TokenManager.getInstance().refreshPayState(true);
                        }else XToastUtils.error(result.getMessage());
                    }
                });
    }

    @SuppressLint("CheckResult")
    private void weiPay(Data_ParkRecord item) {

        CustomRequest request = XHttp.custom();
        request.apiCall(ApiHelper.getInstance(request)
                .weipaynative(item.getTradeNo(), item.getTimestamp(), item.getSign()))
                .subscribeWith(new TipRequestSubscriber<Data_Weipay_Native>() {
                    @Override
                    protected void onSuccess(Data_Weipay_Native data) {
                        String weipayurl = data.getCode_url();
                        createQrCode(weipayurl);
                    }
                });
    }

    private void createQrCode(String weipayurl) {
        if (StringUtils.isEmpty(weipayurl)) {
            XToastUtils.error("二维码内容为空");
            return;
        }
        Bitmap QRcode = XQRCode.createQRCodeWithLogo(weipayurl, 400, 400, null);
        if (QRcode == null) {
            XToastUtils.error("生成二维码失败");
            return;
        }
        new SweetAlertDialog(getContext(), SweetAlertDialog.CUSTOM_IMAGE_TYPE)
                .setContentMinHeight(DensityUtils.dp2px(200))
                .setCustomImage(new BitmapDrawable(QRcode))
                .setContentText("使用微信扫码支付")
                .setCancelText("取消")
                .setConfirmText("支付完成")
                .setCancelClickListener(new SweetAlertDialog.OnSweetClickListener() {
                    @Override
                    public void onClick(SweetAlertDialog sweetAlertDialog) {
                        sweetAlertDialog.dismiss();
                        refresh.autoRefresh();
                    }
                })
                .setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                    @Override
                    public void onClick(SweetAlertDialog sweetAlertDialog) {
//                        sweetAlertDialog.dismiss();
//                        refresh.autoRefresh();
                        gotoSuccess();
                    }
                }).show();
    }

    private void gotoSuccess() {
        TokenManager.getInstance().refreshPayState(true);
        PageOption.to(FragmentPayResult.class)
                .putBoolean(Extras.BASE_SUCCESS_TYPE, true)
                .putString(Extras.BASE_TITLE, "支付结果")
                .putString(Extras.BASE_CODE, "支付成功")
                .putString(Extras.BASE_TYPE, "前往首页")
                .setAddToBackStack(false)
                .open(this);
    }

    private void gotoCoupons(int position) {
        PageOption.to(FragmentAvailableCoupons.class)
                .putInt(Extras.ORDER_CURRENT, position)
                .openForResult(this, Extras.REQUEST_COUPONS);
    }

    @Override
    protected void initListeners() {
        refresh.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                pageIndex++;
                if (orderUnfinish) queryRecordUnFinish(RefreshState.more);
                else queryRecord(RefreshState.more);
            }

            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                pageIndex = 1;
                if (orderUnfinish) queryRecordUnFinish(RefreshState.refresh);
                else queryRecord(RefreshState.refresh);
            }
        });
        refresh.autoRefresh();
    }

    private int pageIndex = 1;

    //请求记录
    private void queryRecord(int flag) {
        new MGetRequest(MyNetApi.PARK_RECORD)
                .user()
                .params(MyNetApi.Park.carNo, number)
                .params(MyNetApi.PageParam.pageSize, 10)
                .params(MyNetApi.PageParam.pageIndex, pageIndex)
                .execute(new TipRequestCallBack<Data_ParkRecord>() {
                    @Override
                    public void onSuccess(Data_ParkRecord data) throws Throwable {
                        queryRecordSuccess(data, flag);
                    }

                    @Override
                    public void onError(ApiException e) {
                        queryRecordError(flag);
                    }
                });
    }

    private void queryRecordUnFinish(int flag) {
        new MGetRequest(MyNetApi.PARK_RECORD_UNFINISH)
                .user()
                .params(MyNetApi.Park.carNo, number)
                .params(MyNetApi.PageParam.pageSize, 10)
                .params(MyNetApi.PageParam.pageIndex, pageIndex)
                .execute(new TipRequestCallBack<Data_ParkRecord>() {
                    @Override
                    public void onSuccess(Data_ParkRecord data) throws Throwable {
                        queryRecordSuccess(data, flag);
                    }

                    @Override
                    public void onError(ApiException e) {
                        queryRecordError(flag);
                    }
                });
    }

    private void queryRecordError(int flag) {
        llState.showError(null);
        switch (flag) {
            case RefreshState.refresh:
                refresh.finishRefresh();
                break;
            case RefreshState.more:
                refresh.finishLoadMore(false);
                break;
        }
    }

    private void queryRecordSuccess(Data_ParkRecord data, int flag) {
        if (data == null || data.getItems() == null) {
            if (flag == RefreshState.refresh) llState.showCustom(emptyStatus());
            return;
        }
        switch (flag) {
            case RefreshState.refresh:
                if (data.getItems().size() == 0) llState.showCustom(emptyStatus());
                else llState.showContent();
                adapterRecords.refresh(data.getItems());
                refresh.finishRefresh();
                if (data.getTotal() == data.getItems().size()) {
                    refresh.setNoMoreData(true);
                }
                break;
            case RefreshState.more:
                adapterRecords.loadMore(data.getItems());
                if (data.getTotal() == adapterRecords.getData().size()) {
                    refresh.finishLoadMoreWithNoMoreData();
                    break;
                }
                refresh.finishLoadMore();
                break;
        }
    }

    @Override
    public void onFragmentResult(int requestCode, int resultCode, Intent data) {
        super.onFragmentResult(requestCode, resultCode, data);
        if (resultCode != RESULT_OK) return;
        if (data == null) return;
        if (requestCode == Extras.REQUEST_COUPONS) updateOrder(data);
        else if (requestCode == Extras.REQUEST_CAR_SELECTE_CAR) updateCarInfo(data);
    }

    private void updateCarInfo(Intent data) {
        String json = data.getStringExtra(Extras.BASE_JSON);
        if (StringUtils.isEmpty(json)) return;
        Data_Car car = JsonUtil.fromJson(json, Data_Car.class);
        if (car == null) return;
        carId = car.getId();
        number = car.getCarNo();
        carIsCetificat = car.isVerified();
        color = car.getPlateColor();
        initCarInfo();
        refresh.autoRefresh();
    }

    private void updateOrder(Intent data) {
        int postiion = data.getIntExtra(Extras.ORDER_CURRENT, -1);
        long id = data.getLongExtra(Extras.BASE_CODE, -1);
        if (postiion == -1) return;
        if (id == -1) queryComputeOrderPrice(postiion, null);
        else queryComputeOrderPrice(postiion, id);
    }

    @SuppressLint("CheckResult")
    private void queryComputeOrderPrice(int postiion, Long id) {
        if (adapterRecords.getItem(postiion) == null) return;
        String orderCode = adapterRecords.getItem(postiion).getOrderNo();
        if (StringUtils.isEmpty(orderCode)) return;
        CustomRequest request = XHttp.custom();
        request.apiCall(ApiHelper.getInstance(request)
                .orderCalculatePrice(orderCode, id))
                .subscribeWith(new TipRequestSubscriber<Data_ParkRecord>() {
                    @Override
                    protected void onSuccess(Data_ParkRecord data) {
                        adapterRecords.refresh(postiion, data);
                    }
                });
    }


    @SingleClick
    @OnClick({R2.id.rtv_exchange_car})
    public void onViewClicked(View view) {
        if (view.getId() == R.id.rtv_exchange_car)
            openPageForResult(FragmentParkingPay.class, Extras.BASE_IS_SELECTED, Extras.BASE_SELECTED, Extras.REQUEST_CAR_SELECTE_CAR);
    }
}
